package com.net.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.dao.redis.IRedislLoginVerifyDao;
import com.util.NetUtil;
/**
 * api请求拦截器
 * 
 * @author 尚业
 *
 */
public class TokenInterceptor implements HandlerInterceptor {
	private static String[] notFilter = new String[] {"register","login","hello"};
	private static Logger logger = Logger.getLogger(TokenInterceptor.class);
	
	@Autowired
	IRedislLoginVerifyDao  redislLoginVerifyDao;
	
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String requestUrl=request.getRequestURI();
		for (String url : notFilter) {
			if ((requestUrl.contains(url))) {		
				return true;
			}
		}
		String token=request.getHeader("JSESSIONID");
		
		if(token==null||token.equals("")){
			String json =JSONObject.toJSON(NetUtil.getCommonFailuerResponse("无token信息")).toString();
//			String json="{\"code\":1,\"body\":\"头部无token信息\"}";
			returnJson(response, json);
			return false;
		}else if(redislLoginVerifyDao.get(token)==null){
			
//			String json="{\"code\":2,\"body\":\"会话过期\"}";
			String json =JSONObject.toJSON(NetUtil.getCommonFailuerResponse("会话过期")).toString();
			returnJson(response, json);
			return false;
		}
		return true;
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	private void returnJson(HttpServletResponse response, String json) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            logger.error("response error",e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }

}
